<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-1.10.2.min.js"></script>
    <script>
        $(function () {
            $("#upload").click(function () {
                var imgFile = $("#headImg")[0].files[0]
                if (imgFile == undefined) {
                    alert("请选择文件")
                    return
                }
                console.log(imgFile)

                var formdata = new FormData()
                formdata.append("img", imgFile)
                $.ajax({
                    type: "post",
                    data: formdata,
                    url: "uploadImg.do",
                    processData: false,
                    contentType: false,
                    success: function (ret) {
                        console.log(ret)
                        alert(ret.msg)
                        $("#head").attr("src", ret.filepath)
                        $("#filetypeInput").val(ret.filetype)
                        $("#photoInput").val(ret.filepath)
                    },
                    xhr: function () {
                        var xhr = new XMLHttpRequest();
                        //使用XMLHttpRequest.upload监听上传过程，注册progress事件，打印回调函数中的event事件
                        xhr.upload.addEventListener('progress', function (e) {
                            //loaded代表上传了多少
                            //total代表总数为多少
                            var progressRate = (e.loaded / e.total) * 100 + '%';
                            //通过设置进度条的宽度达到效果
                            $('.progress > div').css('width', progressRate );
                        })
                        return xhr;
                    }
                })
            })
        })
    </script>

    <style>
        #head {
            width: 200px;
            height: 200px;
        }

        .progress {
            width: 200px;
            height: 10px;
            border: 1px solid #ccc;
            border-radius: 10px;
            margin: 10px 0px;
            overflow: hidden;
        }

        /* 初始状态设置进度条宽度为0px */
        .progress > div {
            width: 0px;
            height: 100%;
            background-color: yellowgreen;
            transition: all .3s ease;
        }
    </style>
</head>
<body>
<form action="registerPlayer.do">
    <p>用户名：<input type="text" name="name"></p>
    <p>密码：<input type="password" name="password"></p>
    <p>昵称：<input type="text" name="nickname"></p>
    <p>头像：<input id="headImg" type="file">
        <input type="button" id="upload" value="上传文件">
    </p>
    <%--进度条--%>
    <div class="progress">
        <div></div>
    </div>
    <p><img id="head" alt="未选择图片"></p>
    <input id="filetypeInput" type="hidden" name="filetype">
    <input id="photoInput" type="hidden" name="photo">
    <p><input type="submit" value="注册"></p>
</form>
</body>
</html>
